//
//  BaseViewController.m
//  
//
//  Created by 黄卫 on 17/2/24.
//  Copyright © 2017年 huangwei. All rights reserved.
//

#import "TYBaseViewController.h"

@interface TYBaseViewController ()

@end

@implementation TYBaseViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        if (!isOfClasses(self,@[@"HealthRecordVC",@"HomeVC",@"MessageVC",@"MineVC"])) {
            self.hidesBottomBarWhenPushed=YES;
        }
        //默认可以从屏幕边缘滑动返回
        canLeftScreenBack = YES;
        
        //全局单例对象
        appGlobalManager = [TYGlobalManager shareInstance];
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self endEdit];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //不加上这句 在iphone 4上会面有问题
    if (self.navigationController.viewControllers.count <= 1) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    
    //由外部控制是否能滑动返回
    if (canLeftScreenBack == NO) {
        self.navigationController.interactivePopGestureRecognizer.enabled = canLeftScreenBack;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //自定义返回按钮
    if (self.navigationController.viewControllers.count > 1) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
        
        //解决自定义返回按钮,滑动返回失效问题
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    }
    
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UITableView class]]&&!view.isHidden) {
            UITableView *table = ((UITableView *)view);
            for (NSIndexPath *p in table.indexPathsForSelectedRows) {
                [table deselectRowAtIndexPath:p animated:YES];
            }
        }
    }
}


///**  iphone 4上面有问题
// *  是否需要屏幕边缘滑动返回, 默认是能滑动返回, 可由外部控制是否能滑动返回
// */
//- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
//{
//    return needLeftScreenBack;
//}

#pragma mark - 监听网络变化

/**
 *  监听网络状态改变 (子类实现该方法处理页面无网逻辑)
 */
- (void)addObsercerNetworkStateChange:(void(^)(AFNetworkReachabilityStatus status))block
{
    NSLog(@"网络发生变化,子类实现该方法处理页面无网逻辑");
    
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        //通知页面处理网络变化
        if (block) {
            block(status);
        }
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                break;
        }
    }];
    // 3.开始监控
    [mgr startMonitoring];
}


#pragma mark - 初始一个导航右侧按钮

- (UIBarButtonItem *)barButtonWithTitle:(NSString *)title titleColor:(UIColor *)color selector:(SEL)selector
{
    return [UIBarButtonItem barButtonWithTitle:title titleColor:color target:self selector:selector];
}

/**
 *  判断导航按右侧钮点击状态
 */
- (void)setRightBarItemEnable:(BOOL)enable
{
    UIButton *rightBtn = self.navigationItem.rightBarButtonItem.customView;
    if ([rightBtn isKindOfClass:[UIButton class]]) {
        rightBtn.enabled = enable;
        [rightBtn setTitleColor:enable ? WhiteColor : [WhiteColor colorWithAlphaComponent:0.4]  forState:UIControlStateNormal];
    } else {
        self.navigationItem.rightBarButtonItem.enabled = enable;
    }
}

#pragma mark - 初始化一个自定义导航

/**
 *  基类导航栏
 */
- (UINavigationBar *)baseNavBar
{
    if (!_baseNavBar) {
        _baseNavBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, (NavigationBar_Height+KStatusBarHeight)-0.3)];
        _baseNavBar.titleTextAttributes = @{NSForegroundColorAttributeName:Color_BlackFont ,NSFontAttributeName:FontCustomSize(16)};
        _baseNavBar.tintColor = WhiteColor;//RGB(112, 112, 112);
        _baseNavBar.barStyle = self.navigationController.navigationBar.barStyle;
        [self.view addSubview:self.baseNavBar];
    }
    return _baseNavBar;
}


/**
 *  获取一个假的导航条
 *  此导航条仅供上一个页面没有导航栏, 下一个页面滑动边缘返回时会顶部异常的情况
 */
- (UINavigationItem *)getNavItemByLeftTitle:(NSString *)leftTitle middleTitle:(NSString *)middleTitle rightTitle:(NSString *)rightTitle
{
    UINavigationItem *navItem = [[UINavigationItem alloc] init];
    
    //返回标题
    CGSize size = [leftTitle sizeWithFont:FontCustomSize(16) constrainedToHeight:45];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, size.width+25, 44)];
    button.titleLabel.font = FontCustomSize(16);
    [button setTitleColor:[WhiteColor colorWithAlphaComponent:0.4] forState:0];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    button.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    [button setImage:ImageNamed(@"navBack_nor") forState:0];
    [button setTitle:leftTitle forState:0];
    navItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    //中间标题
    UILabel *lab = [[UILabel alloc] init];
    lab.font = FontCustomSize(18);
    lab.textColor = WhiteColor;
    lab.text = middleTitle;
    [lab sizeToFit];
    navItem.titleView = lab;
    
    //右边标题
    if (rightTitle) {
        navItem.rightBarButtonItem = [self barButtonWithTitle:rightTitle titleColor:Color_grayFont selector:nil];
    }

    return navItem;
}


/**
 *  返回按钮
 */
- (UIButton *)backBtn
{
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _backBtn.frame = CGRectMake(0, 0, 45, 44);
        _backBtn.titleLabel.font = FontCustomSize(15);
        [_backBtn setTitleColor:WhiteColor forState:0];
        [_backBtn setTitleColor:[WhiteColor colorWithAlphaComponent:0.4] forState:UIControlStateHighlighted];
        _backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
//        [_backBtn setImage:[ImageNamed(@"navBack_nor") imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:0];
        [_backBtn setImage:[UIImage imageNamed:@"navBack_nor"] forState:0];
        [_backBtn addTarget:self action:@selector(popBackVC) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

#pragma mark - 系统处理

/**
 *  点击背景失去第一响应
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self endEdit];
}

/**
 *  失去第一响应
 */
- (void)endEdit
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];;
}

/**
 *  返回上一页面
 */
- (void)popBackVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  返回到指定控制器
 */
- (BOOL)shouldPopToCustomVC:(NSString *)classStr
{
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:NSClassFromString(classStr)]) {
            [self.navigationController popToViewController:vc animated:YES];
            return YES;
        }
    }
    return NO;
}

- (void)dealloc
{
    [NotifyCenter removeObserver:self];
    NSLog(@"释放该页：%s",__FUNCTION__);
}

@end
